package com.chengqs.rapid.core.helper;

import com.chengqs.rapid.common.constants.BasicConst;
import com.chengqs.rapid.common.enums.ResponseCode;
import com.chengqs.rapid.common.util.TimeUtil;
import com.chengqs.rapid.core.context.Context;
import com.chengqs.rapid.core.context.RapidResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.*;

import java.util.Objects;

/**
 * <B>主类名称：</B>ResponseHelper<BR>
 * <B>概要说明：</B>响应的辅助类<BR>
 *
 * @author: chengqs
 * @create: 2025-03-13 02:23:14
 **/
public class ResponseHelper {
    public static FullHttpResponse getHttpResponse(ResponseCode responseCode) {
        RapidResponse rapidResponse = RapidResponse.buildRapidResponse(responseCode);
        DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.INTERNAL_SERVER_ERROR,
                Unpooled.wrappedBuffer(rapidResponse.getContent().getBytes()));
        httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + ";charset=utf-8");
        httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
        return httpResponse;
    }

    /**
     * 通过上下文对象和RapidResponse对象 构建FullHttpResponse
     * @param rapidContext
     * @param rapidResponse
     * @return
     */
    private static FullHttpResponse getHttpResponse(Context rapidContext, RapidResponse rapidResponse) {
        ByteBuf content;
        if (Objects.nonNull(rapidResponse.getFutureResponse())) {
            content = Unpooled.wrappedBuffer(rapidResponse.getFutureResponse().getResponseBodyAsByteBuffer());
        } else if(rapidResponse.getContent() != null) {
            content = Unpooled.wrappedBuffer(rapidResponse.getContent().getBytes());
        } else {
            content = Unpooled.wrappedBuffer(BasicConst.BLANK_SEPARATOR_1.getBytes());
        }

        if(Objects.isNull(rapidResponse.getFutureResponse())) {
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    rapidResponse.getHttpResponseStatus(),
                    content);
            httpResponse.headers().add(rapidResponse.getResponseHeaders());
            httpResponse.headers().add(rapidResponse.getExtraResponseHeaders());
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
            return httpResponse;
        } else {
            rapidResponse.getFutureResponse().getHeaders().add(rapidResponse.getExtraResponseHeaders());

            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.valueOf(rapidResponse.getFutureResponse().getStatusCode()),
                    content);
            httpResponse.headers().add(rapidResponse.getFutureResponse().getHeaders());
            return httpResponse;
        }
    }

    /**
     * 写回响应信息方法
     * @param rapidContext
     */
    public static void writeResponse(Context rapidContext) {
        // 设置SS:
        rapidContext.setSSTime(TimeUtil.currentTimeMillis());

        // 释放资源
        rapidContext.releaseRequest();

        if (rapidContext.isWritten()) {
            // 1：第一步构建响应对象，并写回数据
            FullHttpResponse httpResponse = ResponseHelper.getHttpResponse(rapidContext, (RapidResponse) rapidContext.getResponse());
            if (!rapidContext.isKeepAlive()) {
                rapidContext.getNettyCtx().writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
            } else {
                // 长连接：
                httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                rapidContext.getNettyCtx().writeAndFlush(httpResponse);
            }
            // 2: 设置写回结束状态为：COMPLETED
            rapidContext.completed();
        } else if (rapidContext.isCompleted()){
            rapidContext.invokeCompletedCallback();
        }
    }
}
